package com.lincoln.pictureServer;

import com.lincoln.bean.ApiCode;
import com.lincoln.bean.ApiCodeException;
import com.lincoln.bean.BaseApi;
import com.lincoln.entity.picture.DbPicture;
import com.lincoln.repository.base.BaseRepositoryFactoryBean;
import com.lincoln.service.PictureService;
import com.lincoln.utils.MD5;
import org.apache.catalina.core.ApplicationPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
@EntityScan({"com.lincoln.entity.*.*", "com.lincoln.entity"})
@EnableJpaRepositories(basePackages = {"com.lincoln.repository"},
        repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class//指定自己的工厂类
)
@ComponentScan(basePackages = "com.lincoln.*")
@CrossOrigin
@RestController
public class PictureServerApplication extends BaseApi {
    Logger logger = LoggerFactory.getLogger(PictureServerApplication.class);

    @Value("${picture.win-src}")
    String winSrc;

    @Value("${picture.win-other}")
    String winOther;

    @Value("${picture.linux-src}")
    String linuxSrc;

    @Value("${picture.linux-other}")
    String linuxOther;

    @Autowired
    PictureService pictureService;

    public static void main(String[] args) {
        SpringApplication.run(PictureServerApplication.class, args);
    }

    //<bean id="multiPartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }

    @PutMapping("/picture/upload")
    public ApiCode upload(Integer overt) throws ApiCodeException {
        checkLogin();
        boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") != -1;
        try {
            List<ApplicationPart> parts = (ArrayList) getRequest().getParts();
            for (ApplicationPart part : parts) {
                if (part.getContentType() != null && part.getContentType().indexOf("image/") != -1) {
                    String suffix = part.getSubmittedFileName().substring(part.getSubmittedFileName().indexOf(".") + 1);
                    part.write((isWindows ? winSrc : linuxSrc) + "\\" + part.getSubmittedFileName());
                    File picFile = new File((isWindows ? winSrc : linuxSrc) + "\\" + part.getSubmittedFileName());
                    FileInputStream in = new FileInputStream(picFile);
                    BufferedImage sourceImg = ImageIO.read(in);
                    DbPicture picture = new DbPicture();
                    picture.setContentType(part.getContentType());
                    picture.setHeight(sourceImg.getHeight());
                    picture.setWidth(sourceImg.getWidth());
                    picture.setPicId(MD5.hex_md5(picture.getHeight() + "" + picture.getWidth() + "" + new Date().getTime()));
                    picture.setUser(getUser());
                    picture.setOvert(overt == null ? 0 : overt);
                    in.close();
                    picFile.renameTo(new File((isWindows ? winSrc : linuxSrc) + "\\" + picture.getPicId() + "." + suffix));
                    pictureService.save(picture);
                }
            }
        } catch (Exception e) {
            logger.error("图片上传异常:", e);
            return ApiCode.findCode(ApiCode.PIC_UPLOAD_FAIL);
        }
        return ApiCode.findCode(ApiCode.SUCCESS);
    }
}
